﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using XEvents.Library;

namespace ExtendedEventsManager
{
    public partial class AddEventToSessionForm : Form
    {
        private class PredicateManager
        {
            private List<string> columns = new List<string>();
            private List<string> operators = new List<string>();

            public List<string> Columns
            {
                get { return columns; }
            }

            public List<string> Operators
            {
                get { return operators; }
            }


            public PredicateManager(List<string> predicatecolumns, List<Column> eventcolumns)
            {
                AddDefaultOperators();
                foreach (Column col in eventcolumns)
                {
                    this.columns.Add(col.Name);
                }
                this.columns.AddRange(predicatecolumns);
            }

            private void AddDefaultOperators()
            {
                operators.Add("=");
                operators.Add(">=");
                operators.Add(">");
                operators.Add("<=");
                operators.Add("<");
                operators.Add("!=");
            }
        }

        private class ActionBinder
        {
            public ActionBinder(XEvents.Library.Action action)
            {
                _name = action.Package.Name + "." + action.Name;
                _description = action.Description;
            }

            private bool _selected = false;
            private string _name;
            private string _description;

            public bool Selected
            {
                get { return _selected; }
                set { _selected = value; }
            }

            public string Name
            {
                get { return _name; }
            }
            public string Description
            {
                get { return _description; }
            }

        }

        private SessionEditorForm _parent;
        private List<string> _availablePredicateColumns = new List<string>();
        private List<string> _PredicateComparisons = new List<string>();

        private List<string> columns = new List<string>();
        List<ActionBinder> _ActionList = new List<ActionBinder>();

        BindingSource bs = new BindingSource();

        public AddEventToSessionForm(SessionEditorForm parent)
        {
            InitializeComponent();
            _parent = parent;
            BindPackages();
            PopulateActions();
            this.Text = "Event Editor (" + parent.SessionName + ")";
            this.dgv_EventFields.AutoGenerateColumns = false;
            this.dgv_Actions.AutoGenerateColumns = false;
        }

        public AddEventToSessionForm(SessionEditorForm parent, EventSessionEvent sessionevent)
        {
            InitializeComponent();
            _parent = parent;
            BindPackages();
            PopulateActions();
            this.Text = "Event Editor (" + parent.SessionName + ")";
            this.dgv_EventFields.AutoGenerateColumns = false;
            this.dgv_Actions.AutoGenerateColumns = false;
            BindSessionDataToForm(sessionevent);
        }

        private void BindSessionDataToForm(EventSessionEvent sessionevent)
        {
            Package p = _parent.Session.SqlServer.MetaData.Packages[sessionevent.Name.Split('.').ElementAt(0)];

            cmbx_Package.SelectedValue = p.Name;

            Event e = p.Events[sessionevent.Name.Split('.').ElementAt(1)];

            cmbx_Event.SelectedItem = e;

            txt_Predicate.Text = sessionevent.Predicate;

            for (int i=0; i<dgv_Actions.Rows.Count; i++)
            {
                DataGridViewRow dgvr = dgv_Actions.Rows[i];
                DataGridViewTextBoxCell namecell = (DataGridViewTextBoxCell)dgvr.Cells["dgvActions_Name"];
                DataGridViewCheckBoxCell chkcell = (DataGridViewCheckBoxCell)dgvr.Cells["dgvActions_Selected"];
                if (sessionevent.ActionString.Contains(namecell.Value.ToString()))
                    _ActionList[i].Selected = true;
            }
            bs.ResetBindings(true);
        }
        
        private void PopulateActions()
        {
            _ActionList = (from a in _parent.Session.SqlServer.MetaData.Actions
                          select new ActionBinder(a)).ToList();
            bs.DataSource = _ActionList;
            dgv_Actions.DataSource = bs;
        }

        private void BindPackages()
        {
            List<Package> lp = _parent.Session.SqlServer.MetaData.Packages.PackagesWithEvents;

            cmbx_Package.DataSource = lp;
            cmbx_Package.DisplayMember = "Name";
            cmbx_Package.ValueMember = "Name";

            foreach (Package p in this._parent.Session.SqlServer.MetaData.Packages)
            {
                this._availablePredicateColumns.AddRange((from Predicate pred in p.Predicates
                                                          where pred.PredicateType == PredicateType.Source
                                                          select p.Name + "." + pred.Name).ToList());
                
                this._PredicateComparisons.AddRange((from Predicate pred in p.Predicates
                                                          where pred.PredicateType == PredicateType.Comparator
                                                          select p.Name + "." + pred.Name).ToList());
            }
        }

        private void cmbx_Package_SelectedIndexChanged(object sender, EventArgs e)
        {
            //List<string> obj = (from evnt in Package.Events
            //                    select evnt.Channel).Distinct().ToList();

            //cmbx_Channel.DataSource = obj;
            cmbx_Event.DataSource = (from evnt in Package.Events
                                     //where evnt.Channel == this.Channel
                                     //&& evnt.Keyword == this.Keyword
                                     select evnt).ToList();
            cmbx_Event.DisplayMember = "Name";

        }

        private Package Package
        {
            get { return (Package)cmbx_Package.SelectedItem; }
        }

        //private string Keyword
        //{
        //    get { return (string)cmbx_Keyword.SelectedItem; }
        //}

        private Event Event
        {
            get { return (Event)cmbx_Event.SelectedItem; }
        }


        //private void cmbx_Keyword_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    cmbx_Event.DataSource = (from evnt in Package.Events
        //                             where evnt.Channel == this.Channel
        //                             && evnt.Keyword == this.Keyword
        //                             select evnt).ToList();
        //    cmbx_Event.DisplayMember = "Name";
        //}

        private void cmbx_Event_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Event != null)
            {
                dgv_EventFields.DataSource = Event.Columns;

                columns.Clear();
                columns = (from c in Event.Columns
                           select c.Name).ToList();

                columns.AddRange(_availablePredicateColumns);
                lbl_Description.Text = Event.Description;
            }
        }

        private void btn_Add_Click(object sender, EventArgs e)
        {
            EventSessionEvent se = new EventSessionEvent();
            se.Name = this.cmbx_Package.Text + "." + this.cmbx_Event.Text;

            foreach (DataGridViewRow dgvr in dgv_Actions.Rows)
            {
                DataGridViewCheckBoxCell cell = (DataGridViewCheckBoxCell)dgvr.Cells["dgvActions_Selected"];
                if (Convert.ToBoolean(cell.Value))
                {
                    se.AddAction(dgvr.Cells["dgvActions_Name"].Value.ToString());
                }
            }
            se.Predicate = this.txt_Predicate.Text;
            this._parent.EventBindingSource.Add(se);
            this.DialogResult = DialogResult.OK;
            this.Close();
        }


        private void btn_PredicateEdit_Click(object sender, EventArgs e)
        {
            List<string> predicates = new List<string>();
            predicates.AddRange(this.columns);
            predicates.AddRange(this._availablePredicateColumns);

            ExpressionEditor ee = new ExpressionEditor(predicates.Distinct().ToList(), this._PredicateComparisons, txt_Predicate.Text);
            DialogResult dr = ee.ShowDialog();
            if (dr == DialogResult.OK)
            {
                txt_Predicate.Text = ee.ExpressionValue;
            }
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
    }
}
